package all.com.jinyongqunxiax.decoration;

import android.content.Context;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;


public class EqualSpaceItemDecoration extends RecyclerView.ItemDecoration {
    private int     rowSpace;
    private int     columnSpace;
    private int     spanCount;
    private boolean includeEdge = true;

    public EqualSpaceItemDecoration(Context context, int spanCount, int rowSpace, int columnSpace) {
        this.rowSpace = (int) dimensionValue(context, rowSpace);
        this.columnSpace = (int) dimensionValue(context, columnSpace);
        this.spanCount = spanCount;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildLayoutPosition(view);
        int column   = position % spanCount;

        if (includeEdge) {
            outRect.left = columnSpace - column * columnSpace / spanCount;
            outRect.right = (column + 1) * columnSpace / spanCount;
            // top edge
            if (position < spanCount) {
                outRect.top = rowSpace;
            }
            // item bottom
            outRect.bottom = rowSpace;
        } else {
            outRect.left = column * columnSpace / spanCount;
            outRect.right = columnSpace - (column + 1) * columnSpace / spanCount;
            if (position < spanCount) {
                // item top
                outRect.top = rowSpace;
            }
            // item bottom
            outRect.bottom = rowSpace;
        }
    }

    private float dimensionValue(Context context, int raw) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                raw,
                metrics);
    }
}
